package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import com.sun.tools.corba.se.idl.toJavaPortable.Helper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    SetmealDao setmealDao;
    @Autowired
    JedisPool jedisPool;
    @Autowired
    FreeMarkerConfig freeMarkerConfig;
    @Value("${out_put_path}")
    private String outPutPath;  //从属性名文件中读取要生成的html对应的目录
    @Override
    public Result add(Setmeal setmeal, Integer[] checkgroupIds) {
        try {
            setmealDao.add(setmeal);
            this.setSetmealCheckgroup(setmeal.getId(),checkgroupIds);
            //将图片名称保存到Redis
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());
            generationMobileStaticHtml();
            return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_SETMEAL_FAIL);
        }


    }

    //生成当前方法所需的静态页面
    public void generationMobileStaticHtml() {
        //生成静态页面之前需要查询数据   不包括检查组检查项
        List<Setmeal> list = setmealDao.findAll();
        //需要生成套餐列表的静态页面
        generationMobileSetMealListHtml(list);

        //需要生成套餐详情的静态页面
        generationMobileSetMealDetailHtml(list);
    }

    //生成套餐列表静态页面
    public void generationMobileSetMealListHtml(List<Setmeal> list) {
        Map map = new HashMap();
        //为模板提供数据，用于生成静态页面
        map.put("setmealList", list);
        generationHtml("mobile_setmeal.ftl", "m_setmeal.html", map);
    }

    //生成套餐详情静态页面（有可能多个）
    public void generationMobileSetMealDetailHtml(List<Setmeal> list) {
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal", setmealDao.findById(setmeal.getId()));

            generationHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", map);
        }
    }
    //通用的用于生成静态页面
    public void generationHtml(String templateName, String htmelPageName, Map map) {
        Configuration configuration = freeMarkerConfig.getConfiguration();
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            out = new FileWriter(new File(outPutPath + "/" + htmelPageName));
            template.process(map, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
                try {
                    if (out != null) {
                        out.close();
                        out = null; // 让堆里面的流对象，快速被垃圾回收机制回收 -- 提升内存利用率
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> setmeals =setmealDao.selectByConditon(queryString);
        return new PageResult(setmeals.getTotal(), setmeals.getResult());
    }

    @Override
    public Result findById(Integer id) {
        try {
            Setmeal setmeal = setmealDao.findById(id);
            //用于编辑时保存CheckGroupId
            //List<Integer> checkItemIds = setmealDao.findCheckGroupIdAndSetmeal(id);
            //setmeal.setCheckgroupIds(checkItemIds);
            return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS, setmeal);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_SETMEAL_FAIL);
        }

    }

    @Override
    public Result findAll() {
        try {
            List<Setmeal> setmealList = setmealDao.findAll();
            return new Result(true, MessageConstant.QUERY_SETMEALLIST_SUCCESS, setmealList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, MessageConstant.QUERY_SETMEALLIST_FAIL);
        }
    }

    @Override
    public Result getSetmealReport() {
        List<Setmeal> setmealList = setmealDao.findAll();
        List<String> setmealNames = new ArrayList<>();
        List<Map<String, Object>> accounts = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        for (Setmeal setmeal : setmealList) {
            String setmealName = setmeal.getName();
            setmealNames.add(setmealName);


            Integer id = setmeal.getId();
            //获取value
            int account = setmealDao.selectAccountById(id);
            if (account > 0) {
                map.put("name", setmealName);
                map.put("value", account);
                //添加一个套餐对应的数据
                accounts.add(map);
            }
        }
        Map<String, Object> data = new HashMap<>();
        data.put("setmealNames", setmealNames);
        data.put("setmealCount", accounts);
        return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, data);
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();

    }

    public void setSetmealCheckgroup( Integer setmealId,Integer[] checkgroupIds) {
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                HashMap<String, Integer> map = new HashMap<>();
                map.put("checkgroup_id", checkgroupId);
                map.put("setmeal_id", setmealId);
                setmealDao.addSetmealCheckgroup(map);
            }

        }
    }
}
